<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>最终版人员分组管理系统</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<!--    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>-->
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .section {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h2 {
            color: #333;
            border-bottom: 2px solid #eee;
            padding-bottom: 10px;
            margin-top: 0;
        }
        .group-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
        }
        .group-item {
            flex: 1;
            min-width: 150px;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 5px;
            border-left: 4px solid #4CAF50;
            position: relative;
        }
        .group-title {
            font-weight: bold;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
        }
        .group-actions {
            position: absolute;
            top: 5px;
            right: 5px;
        }
        .group-actions button {
            background: none;
            border: none;
            cursor: pointer;
            padding: 2px;
            font-size: 12px;
            color: #666;
        }
        .group-actions button:hover {
            color: #333;
        }
        .group-members {
            min-height: 50px;
            margin-top: 25px;
        }
        .member-item {
            padding: 5px;
            margin: 3px 0;
            background: #e9e9e9;
            border-radius: 3px;
        }
        .btn {
            padding: 8px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .btn-primary {
            background: #4CAF50;
            color: white;
        }
        .btn-primary:hover {
            background: #45a049;
        }
        .btn-secondary {
            background: #2196F3;
            color: white;
        }
        .btn-secondary:hover {
            background: #0b7dda;
        }
		.btn-danger{
			background: orange;
			color: white;
		}
        textarea {
            width: 100%;
            height: 100px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
            resize: vertical;
        }
        .people-list {
            margin-top: 15px;
        }
        .person-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            margin-bottom: 8px;
            background: #f9f9f9;
            border-radius: 5px;
        }
        select {
            padding: 5px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        .empty-state {
            color: #999;
            text-align: center;
            padding: 20px;
        }
        .edit-input {
            width: 80%;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }

        input{
            line-height: 27px;
            position: relative;
            bottom: 2px;
            margin-bottom: 10px;
            margin-right: 10px;
        }

        textarea{
            margin-top: 10px;
        }

        .container-flex {
            display: flex;
            justify-content: space-between;
        }

        .contactInformation{
            text-align: center;
            padding: 5px;
            font-size: 12px;
        }

        #dialog-changeGroup{
            text-align: center;
            padding: 20px;
        }
        #dialog-changeGroup button{
            margin: 10px;
            width: 60px;
        }

        .link{
            cursor: pointer;
        }

        .table-round{
            border: solid 1px gray;
            width: 100%;
        }
        .table-round thead th{
            text-align: center;
            font-weight: bold;
        }

        .table-round tbody td{
            text-align: center;
            font-weight: bold;
            border-top: solid 1px gray;
            height: 23px;
        }

        .table-round tbody td{
            border-right: solid 1px gray;
        }

        .table-round tbody tr td:last-child{
            border-right: solid 0px gray;
        }

        .ui-widget-overlay {
            background: #070707;
            opacity: 0.5;
            filter: Alpha(Opacity=30);
        }
    </style>
</head>
<body>
    <h1>羽毛球大循环赛管理系统</h1>
    
    <div class="section">
        <h2>分级管理 <span style="font-weight: normal;font-size:15px;color: #4CAF50">(第一级别为队长,不需要的级别请删除)</span></h2>
        <div class="group-container" id="groupContainer">
            <!-- 分组将在这里动态生成 -->
        </div>
        <div style="margin-top: 15px;">
            <input type="text" id="newGroupName" placeholder="输入新组名">
            <button class="btn btn-primary" onclick="addGroup()">添加分组</button>
        </div>
    </div>
    
    <div class="section">
        <h2>人员管理</h2>
        <div>
            <button class="btn btn-secondary" onclick="batchAddPeople()">批量添加</button>
			<button class="btn btn-danger" onclick="clearPeople()">清空</button>
            <textarea id="batchInput" placeholder="批量粘贴人员名单，每行一个人"></textarea>
            <!-- <input type="text" id="newPersonName" placeholder="或输入单个人员姓名" style="width: 200px; margin-left: 10px;"> -->
            <!-- <button class="btn btn-primary" onclick="addPerson()">添加</button> -->
        </div>
        <div class="people-list" id="peopleList">
            <!-- 人员列表将在这里动态生成 -->
        </div>
    </div>

    <div class="section">
        <h2>级别分组人员展示</h2>
        <input type="text" id="matchName" placeholder="请输入比赛名称" /> <br>
        <button class="btn btn-secondary" onclick="getPlayList()">生成对阵表</button>
        <button class="btn btn-secondary" onclick="randomTeams()">随机组队</button>
        <div class="group-container" id="groupDisplay">
            <!-- 分组人员将在这里动态展示 -->
        </div>
    </div>

    <div class="section">
        <div class="contactInformation link">
            <span onclick="privacyAgreement()">隐私协议</span>
            &nbsp;&nbsp;
            <span onclick="advertising()">广告服务</span>
            &nbsp;&nbsp;
            <span onclick="userAgreement()">用户协议</span>
        </div>
        <div class="contactInformation link">
            <span>联系方式: 邮箱: yulinmdl@163.com</span>
            <span>微信: 雨润林馨</span>
        </div>
    </div>

    <div id="dialog-privacyAgreement" title="隐私协议" hidden="hidden">
        <p>本软件尊重并保护所有使用服务用户的个人隐私权。为了给您提供更准确、更有个性化的服务，本软件会按照本隐私权政策的规定使用和披露您的个人信息。
            但本软件将以高度的勤勉、审慎义务对待这些信息。除本隐私权政策另有规定外，在未征得您事先许可的情况下，本软件不会将这些信息对外披露或向第三
            方向任何第三方提供、出售、出租、分享或转让您的个人信息，但以下情况除外：
        </p>
        <p>1. 本软件根据法律法规或有权机关的要求，向第三方或公众披露您的个人信息，以防止损害您及公众或其他用户的人身财产安全，或维护本软件的合法权益。</p>
        <p>2. 在涉及合并、收购或破产清算时，如涉及到个人信息转让，本软件会要求新的持有您个人信息的公司、组织继续受本隐私权政策的约束，否则本软件将要求该公司、组织重新向您征求授权同意。</p>
        <p>3. 如您出现违反中国有关法律、法规或者本软件服务协议或相关规则的情况，需要向第三方披露。</p>
        <p>4. 为维护本软件服务的正常运行及安全，发现、处置存在异常的账户状态时。</p>
        <p>5. 根据法律规定，对于您明确同意向第三方披露的信息，本软件不承担任何保护、不披露和个人信息安全的责任。</p>
        <p>6. 本隐私权政策中涉及您个人信息的相关内容，本软件将按照法律法规的要求，采取合理可行的措施进行删除、匿名化处理或限制处理，以保护您的隐私。</p>
        <p>7. 上面说的其实都没啥用,当前页面目前只是单文件版本,不涉及网络传输内容,所以你的隐私是完全安全的。</p>
    </div>

    <div id="dialog-advertising" title="隐私协议" hidden="hidden">
        <p>想多了,都不联网哪来的广告,闹着玩的</p>
    </div>
    <div id="dialog-userAgreement" title="用户协议" hidden="hidden">
        <p>1. 本软件是本人业余时间自己设计,自行开发,为羽毛球比赛做的纯免费简单工具. 如遇到bug,报错,结果错误等情况,本人概不负责</p>
        <p>2. 软件不涉及版权问题,业余羽毛球比赛没什么经费,如果能用,或者好用,欢迎扩散传播,给大家提供方便</p>
        <p>3. 本人是后端开发,前端纯属玩票,如果发现问题,或者有好的建议,可以发送到我的邮箱 yulinmdl@163.com ,如果有时间我会更正bug,没时间就拉倒</p>
        <p>4. 本人对代码有全部版权,禁止利用当前代码进行服务扩展,开发引用及收费</p>
    </div>
    <div id="dialog-changeGroup" title="选择分组" hidden="hidden">

    </div>


    <script>
        function advertising(){
            $( "#dialog-advertising" ).dialog({
                resizable: false,height: "auto",width: 300,height: 250,modal: true
            });
        }
        //隐私协议
        function privacyAgreement(){
            $( "#dialog-privacyAgreement" ).dialog({
                resizable: false,height: "auto",width: 300,height: 500,modal: true
            });
        }
        function userAgreement(){
            $( "#dialog-userAgreement" ).dialog({
                resizable: false,height: "auto",width: 300,height: 500,modal: true
            });
        }

        // 初始化默认分组
		let groups = JSON.parse(localStorage.getItem('groups'))
		
		if(!groups || groups.length==0){
			groups =  [
				{ id: 1, name: 'A+', members: [] },
				{ id: 2, name: 'A-', members: [] },
				{ id: 3, name: 'B+', members: [] },
				{ id: 4, name: 'B-', members: [] },
				{ id: 5, name: 'C', members: [] }
			];
		}
		
        
        let people = JSON.parse(localStorage.getItem('people')) || [];
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            renderAll();
        });
		
		
		function generateSecureId() {
		    const array = new Uint32Array(1);
		    window.crypto.getRandomValues(array);
		    return array[0].toString(36);
		}
        
        // 批量添加人员
        function batchAddPeople() {
            const input = document.getElementById('batchInput').value.trim();
            if (!input) return;
            
            const names = input.split('\n').filter(name => name.trim());
            names.forEach(name => {
				const id = generateSecureId()

                //如果name以数字+.开头,用正则匹配并去掉数字部分
                if(name.match(/^\d+\.\s*/)){
                    name = name.replace(/^\d+\.\s*/, '');
                }

                const newPerson = {
                    id: id,
                    name: name.trim(),
                    groupId: null
                };
                people.push(newPerson);
            });
            
            saveData();
            renderAll();
            document.getElementById('batchInput').value = '';
        }
        
        // 添加单个人员
        function addPerson() {
            const personName = document.getElementById('newPersonName').value.trim();
            if (!personName) return;
            
			const id = generateSecureId()
            const newPerson = {
                id: id,
                name: personName,
                groupId: null
            };
            
            people.push(newPerson);
            saveData();
            renderAll();
            document.getElementById('newPersonName').value = '';
        }
        
        // 添加新分组
        function addGroup() {
            const groupName = document.getElementById('newGroupName').value.trim();
            if (!groupName) return;
            
            const newGroup = {
                id: Date.now(),
                name: groupName,
                members: []
            };
            
            groups.push(newGroup);
            saveData();
            renderAll();
            document.getElementById('newGroupName').value = '';
        }
        
        // 删除人员
        function deletePerson(personId) {
            if (confirm('确定要删除这个人员吗？')) {
                // 从所在分组中移除
                const person = people.find(p => p.id === personId);
                if (person && person.groupId) {
                    const group = groups.find(g => g.id === person.groupId);
                    if (group) {
                        group.members = group.members.filter(id => id !== personId);
                    }
                }
                
                // 删除人员
                people = people.filter(p => p.id !== personId);
                saveData();
                renderAll();
            }
        }
        
        // 重命名分组
        function renameGroup(groupId) {
            const group = groups.find(g => g.id === groupId);
            if (!group) return;
            
            const newName = prompt('请输入新的分组名称:', group.name);
            if (newName && newName.trim() && newName.trim() !== group.name) {
                group.name = newName.trim();
                saveData();
                renderAll();
            }
        }
        
        // 删除分组
        function deleteGroup(groupId) {
            const group = groups.find(g => g.id === groupId);
            if (!group) return;
            
            if (confirm(`确定要删除"${group.name}"分组吗？组内成员将变为未分组状态`)) {
                // 将该分组的人员设为未分组
                people.forEach(person => {
                    if (person.groupId === groupId) {
                        person.groupId = null;
                    }
                });
                
                // 删除分组
                groups = groups.filter(g => g.id !== groupId);
                saveData();
                renderAll();
            }
        }
        
        // 更新人员分组
        function updatePersonGroup(personId, groupId) {
            const person = people.find(p => p.id === personId);
            if (!person) return false;
            
            // 从原分组移除
            if (person.groupId) {
                const oldGroup = groups.find(g => g.id === person.groupId);
                if (oldGroup) {
                    oldGroup.members = oldGroup.members.filter(id => id !== personId);
                }
            }
            
            // 添加到新分组
            person.groupId = groupId === 'null' ? null : parseInt(groupId);
            if (person.groupId) {
                const newGroup = groups.find(g => g.id === person.groupId);
                if (newGroup && !newGroup.members.includes(personId)) {
                    newGroup.members.push(personId);
                }
            }
            
            saveData();
            // 强制同步刷新所有区域
            setTimeout(() => {
                renderGroups();
                renderPeople();
                renderGroupDisplay();
            }, 0);
            return true;
        }
		
		// 修改分组选择事件处理
        function setupGroupSelectEvents() {
            document.querySelectorAll('#peopleList select').forEach(select => {
                select.onchange = function() {
                    const personId = this.dataset.personId;
                    const success = updatePersonGroup(personId, this.value);
                    if (!success) {
                        this.value = people.find(p => p.id === personId).groupId || 'null';
                    }
                };
            });
        }
        
        // 渲染所有区域
        function renderAll() {
            renderGroups();
            renderPeople();
            renderGroupDisplay();
        }
        
        // 渲染分组
        function renderGroups() {
            const groupContainer = document.getElementById('groupContainer');
            groupContainer.innerHTML = '';
            
            groups.forEach(group => {
                const groupElement = document.createElement('div');
                groupElement.className = 'group-item';
                groupElement.innerHTML = `
                    <div class="group-actions">
                        <button onclick="renameGroup(${group.id})" title="重命名">✏</button>
                        <button onclick="deleteGroup(${group.id})" title="删除">🗑️</button>
                    </div>
                    <div class="group-title">${group.name}</div>
                `;
                groupContainer.appendChild(groupElement);
            });
        }
        
        // 渲染人员列表
        function renderPeople() {
            const peopleList = document.getElementById('peopleList');
            if (people.length === 0) {
                peopleList.innerHTML = '<div class="empty-state">暂无人员，请添加</div>';
                return;
            }
            
            peopleList.innerHTML = '';
            people.forEach(person => {
                const personElement = document.createElement('div');
                personElement.className = 'person-item';
                personElement.innerHTML = `
                    <div>${person.name}</div>
                    <div>
                        <select data-person-id="${person.id}">
                            <option value="null">未分组</option>
                            ${groups.map(g => 
                                `<option value="${g.id}" ${person.groupId === g.id ? 'selected' : ''}>${g.name}</option>`
                            ).join('')}
                        </select>
                        <button class="btn btn-danger" onclick="deletePerson('${person.id}')">删除</button>
                    </div>
                `;
                peopleList.appendChild(personElement);
            });
            
            // 重新绑定事件
            setupGroupSelectEvents();
        }
		
        // 渲染分组展示区域
        function renderGroupDisplay() {
            const groupDisplay = document.getElementById('groupDisplay');
            groupDisplay.innerHTML = '';
            
            groups.forEach(group => {
                const groupElement = document.createElement('div');
                groupElement.className = 'group-item';
                groupElement.innerHTML = `
                    <div class="group-title">
                        <span>${group.name}组 (${group.members.length}人)</span>
                    </div>
                    <div class="group-members">
                        ${group.members.length > 0 ? 
                            group.members.map(memberId => {
                                const member = people.find(p => p.id === memberId);
                                return member ? `<div class="member-item container-flex" data-person-id="${member.id}">
                                                    ${member.name}
                                                    <button class="btn btn-primary" style="padding: 3px 12px !important;" onclick="changeGroup(this)">切换</button>
                                                </div>` : '';
                            }).join('') :
                            '<div class="empty-state">暂无成员</div>'}
                    </div>
                `;
                groupDisplay.appendChild(groupElement);
            });
        }

        function changeGroup(obj){
            const personId = obj.parentElement.getAttribute('data-person-id');
            const person = people.find(p => p.id === personId);

            $("#dialog-changeGroup").empty()
            $("#dialog-changeGroup").append(`<input type="hidden" name="personId" value="${personId}"  />`)
            groups.forEach(group => {
                $("#dialog-changeGroup").append(
                    `<button type="button" class="btn btn-primary" value="${group.id}" onclick="change(this)">${group.name}</button><br>`
                )
            })

            $( "#dialog-changeGroup" ).dialog({
                resizable: false,height: "auto",width: 300,height: 400,modal: true,
                buttons: {
                    "取消": function() {
                        $( this ).dialog( "close" );
                    }
                }
            });
        }

        function change(obj){
            const personId = $(obj).parent().find("input[name='personId']").val();
            const groupId = parseInt($(obj).val());
            console.log(groups)

            //根据groupId ,把personId从原来的组里移除,添加到新的组里
            for (const group of groups) {
                //删除当前personId
                removeBySplice(group.members, personId)

                //添加当前persionId
                if (group.id == groupId) {
                    group.members.push(personId);
                }
            }

            //people里更新personId对应的groupID
            people.find(p => p.id === personId).groupId = groupId;;

            //重新渲染
            renderAll();
            //切换 data-person-id=personId 的 select 的值
            $(`select[data-person-id='${personId}']`).val(groupId);
            $("#dialog-changeGroup" ).dialog( "close" );

            //保存到localStorage
            saveData();
        }

        function removeBySplice(arr, target) {
            const index = arr.indexOf(target);
            if (index > -1) arr.splice(index, 1);
            return arr;
        }

        // 保存数据
        function saveData() {
            localStorage.setItem('groups', JSON.stringify(groups));
            localStorage.setItem('people', JSON.stringify(people));
        }

		function clearPeople(){
			if(confirm("确定要清空全部人员吗？")){
                // 清空人员数组
                people = [];

                // 保存到 localStorage
				localStorage.removeItem('people')


                // 清空所有找到的 div 元素
				const divs = document.querySelectorAll('.people-list div');
				
				// 清空人员列表564
				const container = document.querySelector('.people-list');
				while (container.firstChild) {
					container.removeChild(container.firstChild);
				}

				// 清空分组里的人员
				document.querySelectorAll('.group-members').forEach(element => {
					element.remove();
				});

                groups.forEach(
                    group => group.members = []
                )
                localStorage.setItem('groups', JSON.stringify(groups));

                // 渲染人员列表
                renderAll()
			}
			
		}


        //遍历轮次数组,输出对阵列表
        function renderRoundAll(roundAry){
            let lines='';
            let linesNum=0;

            let roundNum = 0;
            for (const round of roundAry) {
                roundNum++;

                let i=0
                for (const match of round) {
                    let firstCell=''
                    if(i==0){
                        firstCell = `<td rowspan="${round.length}">第${roundNum}轮</td>`
                    }


                    lines +=
                        `<tr>
                            ${firstCell}
                            <td></td>
                            <td>${match[0]} vs ${match[1]}</td>
                            <td></td>
                            <td></td>
                        </tr>`

                    i++;
                    linesNum++;
                }

                let breakAfter = ''
                if(linesNum%25==0){
                    breakAfter = 'break-after'
                }
                lines += `<tr class="${breakAfter}"><td colspan="5"></td></tr>`

            }

            const matchName = $("#matchName").val();

            const html =
                `<div class="table-round-container">
                    <div class="table-round-title">
                        <b>${matchName}</b>(大循环)<b>友谊赛</b><br>
                        对阵记录表
                    </div>
                    <table class="table-round">
                        <thead>
                            <tr>
                                <th>轮次</th>
                                <th>场地</th>
                                <th>对阵双方</th>
                                <th>比分情况</th>
                                <th>备注</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${lines}
                        </tbody>
                    </table>
                </div>`

            // $("body").append(html)

            //打开新页面,并嵌入html
            let win = window.open();
            win.document.write(html);

            const style=
                `<style>
                    .break-after {
                      break-after: always; /* 或者使用 always, left, right, recto, verso 等 */
                    }
                    .table-round-container{
                        margin: 0 auto;
                        padding: 35px;
                        text-align: center;
                        font-size: 14px;
                        font-family: Arial, sans-serif;
                        margin-top: 50px;
                    }
                    .table-round-title{
                        margin-bottom: 20px;
                        font-size: 30px;
                        font-family: Arial, sans-serif;

                    }
                   .table-round{
                        border: solid 1px gray;
                        width: 100%;
                    }
                    .table-round thead th{
                        text-align: center;
                        font-weight: bold;
                        border-right: solid 1px gray;
                    }

                    .table-round tbody td{
                        text-align: center;
                        border-top: solid 1px gray;
                        height: 23px;
                        border-right: solid 1px gray;
                    }


                    .table-round tbody tr td:last-child{
                        border-right: solid 0px gray;
                    }
                    .table-round thead tr th:last-child{
                        border-right: solid 0px gray;
                    }
                </style>`
            win.document.write(style);
            win.document.close();
            // win.focus();

        }



        //获得对战页面列表
        function getPlayList(){
            //队长列表
            let captains = [];

            //取出people中分组为1的全部name
            for (const person of people) {
                if (person.groupId == 1) {
                    captains.push(person.name);
                }
            }

            //根据队长列表,生成每轮对战列表
            const resultAry = generateRoundRobin(captains)

            //渲染对战页面
            renderRoundAll(resultAry)

        }

        //生成循环赛对战列表
        function generateRoundRobin(players) {
            if (players.length % 2 !== 0) {
                players.push('BYE'); // 处理奇数选手情况
            }

            const numPlayers = players.length;
            const rounds = numPlayers - 1;
            const half = numPlayers / 2;
            const tournament = [];

            for (let round = 0; round < rounds; round++) {
                const roundMatches = [];
                for (let i = 0; i < half; i++) {
                    const player1 = players[i];
                    const player2 = players[numPlayers - 1 - i];
                    if (player1 !== 'BYE' && player2 !== 'BYE') {
                        roundMatches.push([player1, player2]);
                    }
                }
                tournament.push(roundMatches);

                // 轮转数组（保持第一个元素固定）
                players.splice(1, 0, players.pop());
            }
            return tournament;
        }

        //按级别组队
        function generateTeams(levelGroups) {
            // 验证输入数据
            if (!levelGroups || levelGroups.length === 0) {
                throw new Error('级别组数组不能为空');
            }

            //监察每个级别人员数量是否一样
            const groupsLength = levelGroups.length
            const firstGroupLength = levelGroups[0].members.length;
            for (let i = 1; i < groupsLength; i++) {
                if (levelGroups[i].members.length !== firstGroupLength) {
                    alert('每个级别的人员数量必须相同');
                    return;
                }
            }


            const memberCount = levelGroups[0].members.length;
            const teamCount = memberCount; // 战队数量等于每个级别的成员数
            const teams = Array(teamCount).fill().map(() => []);

            // 对每个级别进行随机洗牌
            const shuffledLevels = levelGroups.map(level => ({
                ...level,
                members: [...level.members].sort(() => Math.random() - 0.5)
            }));

            // 分配成员到战队
            for (let i = 0; i < teamCount; i++) {
                for (const level of shuffledLevels) {
                    teams[i].push({
                        level: level.name,
                        member: level.members[i]
                    });
                }
            }

            //根据编码获得人名
            for (const team of teams) {
                for (const people of team) {
                    people.name= getNameByCode(people.member);
                }

            }

            return teams;
        }

        //遍历轮次数组,输出对阵列表
        function renderRoundAll(roundAry){
            let lines='';
            let linesNum=0;

            let roundNum = 0;
            for (const round of roundAry) {
                roundNum++;

                let i=0
                for (const match of round) {
                    let firstCell=''
                    if(i==0){
                        firstCell = `<td rowspan="${round.length}">第${roundNum}轮</td>`
                    }


                    lines +=
                        `<tr>
                            ${firstCell}
                            <td></td>
                            <td>${match[0]} vs ${match[1]}</td>
                            <td></td>
                            <td></td>
                        </tr>`

                    i++;
                    linesNum++;
                }

                let breakAfter = ''
                if(linesNum%25==0){
                    breakAfter = 'break-after'
                }
                lines += `<tr class="${breakAfter}"><td colspan="5"></td></tr>`

            }

            const matchName = $("#matchName").val();

            const html =
                `<div class="table-round-container">
                    <div class="table-round-title">
                        <b>${matchName}</b>(大循环)<b>友谊赛</b><br>
                        对阵记录表
                    </div>
                    <table class="table-round">
                        <thead>
                            <tr>
                                <th>轮次</th>
                                <th>场地</th>
                                <th>对阵双方</th>
                                <th>比分情况</th>
                                <th>备注</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${lines}
                        </tbody>
                    </table>
                </div>`

            // $("body").append(html)

            //打开新页面,并嵌入html
            let win = window.open();
            win.document.write(html);

            const style=
                `<style>
                    .break-after {
                      break-after: always; /* 或者使用 always, left, right, recto, verso 等 */
                    }
                    .table-round-container{
                        margin: 0 auto;
                        padding: 35px;
                        text-align: center;
                        font-size: 14px;
                        font-family: Arial, sans-serif;
                        margin-top: 50px;
                    }
                    .table-round-title{
                        margin-bottom: 20px;
                        font-size: 30px;
                        font-family: Arial, sans-serif;

                    }
                   .table-round{
                        border: solid 1px gray;
                        width: 100%;
                    }
                    .table-round thead th{
                        text-align: center;
                        font-weight: bold;
                        border-right: solid 1px gray;
                    }

                    .table-round tbody td{
                        text-align: center;
                        border-top: solid 1px gray;
                        height: 23px;
                        border-right: solid 1px gray;
                    }


                    .table-round tbody tr td:last-child{
                        border-right: solid 0px gray;
                    }
                    .table-round thead tr th:last-child{
                        border-right: solid 0px gray;
                    }
                </style>`
            win.document.write(style);
            win.document.close();
            // win.focus();

        }


        //随机组队
        function randomTeams(){
            //按级别组队
            let teams = generateTeams(groups)
            //战队列表
            console.log(teams);

            //渲染对战页面
            renderAllTeams(teams)
        }

        function getTeamsTitle() {
            let title = ''
            for (let i = 0; i < groups.length; i++) {
                if(i==0){
                    title += `<th>队长</th>`
                }else{
                    title += `<th>队员${i}</th>`
                }
            }
            return title;
        }

        //遍历战队数组,输出全部战队队员信息
        function renderAllTeams(teams){
            let lines='';
            let linesNum=0;

            for (const team of teams) {
                let i=0
                let cells=''
                for (const people of team) {
                    if(i==0){
                        cells += `<td >${people.name}</td>`
                    }else{
                        cells += `<td >${people.name}</td>`
                    }


                    i++;
                    linesNum++;
                }
                lines +=
                    `<tr>
                        ${cells}
                    </tr>`

            }

            const matchName = $("#matchName").val();

            const html =
                `<div class="table-round-container">
                    <div class="table-round-title">
                        <b>${matchName}</b>(大循环)<b>友谊赛</b><br>
                        战队列表
                    </div>
                    <table class="table-round">
                        <thead>
                            <tr>
                                ${getTeamsTitle()}
                            </tr>
                        </thead>
                        <tbody>
                            ${lines}
                        </tbody>
                    </table>
                </div>`

            // $("body").append(html)

            //打开新页面,并嵌入html
            let win = window.open();
            win.document.write(html);

            const style=
                `<style>
                    .break-after {
                      break-after: always; /* 或者使用 always, left, right, recto, verso 等 */
                    }
                    .table-round-container{
                        margin: 0 auto;
                        padding: 35px;
                        text-align: center;
                        font-size: 14px;
                        font-family: Arial, sans-serif;
                        margin-top: 50px;
                    }
                    .table-round-title{
                        margin-bottom: 20px;
                        font-size: 30px;
                        font-family: Arial, sans-serif;

                    }
                   .table-round{
                        border: solid 1px gray;
                        width: 100%;
                    }
                    .table-round thead th{
                        text-align: center;
                        font-weight: bold;
                        border-right: solid 1px gray;
                    }

                    .table-round tbody td{
                        text-align: center;
                        border-top: solid 1px gray;
                        height: 23px;
                        border-right: solid 1px gray;
                    }


                    .table-round tbody tr td:last-child{
                        border-right: solid 0px gray;
                    }
                    .table-round thead tr th:last-child{
                        border-right: solid 0px gray;
                    }
                </style>`
            win.document.write(style);
            win.document.close();
            // win.focus();

        }

        //根据编码获得人名
        function getNameByCode(id){
            for (const person of people) {
                if(person.id === id){
                    return person.name;
                }
            }
            return null;
        }


        //全部人员
        // console.log(people)
        //级别分组
        // console.log(groups)





    </script>
</body>
</html>
